<?php

namespace Atom;
/*
 * @date 2020-7-30
 * @author 原子工作室 Atom Studio
 * @description 采集华军网app的数据
 * */
//添加 composer
define( "COMPOSER_PATH", get_template_directory() . '/vendor/' );
require COMPOSER_PATH . 'autoload.php';
require COMPOSER_PATH . 'jaeger/querylist/src/QueryList.php';

use QL\Dom\Query;
use Ql\QueryList;

class Collection {
	var $rules = [
		'app'          => [
			'post_title'   => [ '.name.mname .ofname', 'html' ],
			'post_content' => [ '#ItemRJJS .cont .imginfo .imginfoWrap', 'html', '-.xianssort -.xbtj a' ],
			'icon'         => [ '.softDownIfTop img', 'src' ],
			'seo_title'    => [ '.softdtmb', 'text' ],
			'seo_desc'     => [ '#ItemRJJS .cont .imginfo .imginfoWrap > .text', 'text' ],

		],
		'app_list'     => [
			'title' => [ 'h2 a', 'text' ],
			'url'   => [ 'h2 a', 'href' ]
		],
		'screenshot'   => [
			'screenshot' => [ 'img', 'src' ]
		],
		'app_comments' => [
			'comment_content' => [ '.plcontent span', 'text' ],
			'comment_date'    => [ '.cominfo .utime', 'text' ],
		],
		'meta'         => [
			'version'     => [ '#soft_detail', 'text' ],
			'auth'        => [ 'li:nth-child(3) > span:last', 'text' ],
			'type'        => [ 'li:nth-child(4) > span:last', 'text' ],
			'language'    => [ 'li:nth-child(5) > span:last', 'text' ],
			'create_time' => [ 'li:nth-child(6) > span:last', 'text' ],
			'platform'    => [ 'li:nth-child(7) > span:last', 'text' ],
			'size'        => [ 'li:nth-child(9) > span:last', 'text' ],
		]
	];

	function __construct() {
		add_action( 'admin_menu', [ $this, 'settings_page' ] );
		$this->set_ajax_func();
	}

	public function settings_page() {
		add_menu_page( '采集', '采集', 'manage_options', 'collection', [
			$this,
			'settings_page_content'
		], get_template_directory_uri() . '/images/icon_home.png', 10 );
	}

	public function settings_page_content() {
		ob_start();
		get_template_part( 'include/admin/setting' );
		$page = ob_get_contents();
		ob_clean();

		echo $page;
	}

	public function set_ajax_func() {
		add_action( 'wp_ajax_get_term', [ $this, 'get_term' ] );
		add_action( 'wp_ajax_get_pages', [ $this, 'get_pages' ] );
		add_action( 'wp_ajax_run', [ $this, 'run' ] );
	}

	public function get_term() {
		$term = get_terms( [
			'hide_empty' => false,
		] );
		wp_send_json( [ 'code' => 200, "data" => $term ] );
		wp_die();
	}


	public function download_and_get_attach_id($attach_uri) {
		$up_path = wp_upload_dir();
		$attach = file_get_contents($attach_uri);

		$file_info = pathinfo( parse_url( $attach_uri, PHP_URL_PATH ) );
		$basename = strtolower($file_info['basename']);
		$dir_path = $up_path['path'] . '/' . $basename;
		$url_path = $up_path['url']  . '/' . $basename;

		//保存文件到 $dir_path
		file_put_contents( $dir_path, $attach, FILE_USE_INCLUDE_PATH );
		$mime = wp_get_image_mime( $dir_path );
		$attach_id   = wp_insert_attachment( [
			'guid'           => $url_path,
			'post_mime_type' => $mime,
			'post_title'     => $file_info['filename'],
			'post_content'    => '',
			'post_status'    => 'inherit',

		], $dir_path, 0 );

		if (is_wp_error($attach_id)) {
			return $attach_id->get_error_message();
		} else {
			$attach_data = wp_generate_attachment_metadata( $attach_id, $url_path );
			wp_update_attachment_metadata( $attach_id, $attach_data );

			return $attach_id;
		}
	}

	/*采集文章*/
	public function get_app( $url ) {

		$ql   = QueryList::get( $url );
		$data = [];

		$data['screenshot'] = $ql->rules( $this->rules['screenshot'] )->range( "#ItemRJJS > .cont:nth-child(2) > .imginfo > .imginfoWrap .text p" )->queryData();

		if ( count( $data['screenshot'] ) ) {
			foreach ( $data['screenshot'] as $k => $v ) {
				if ( $v['screenshot'] === '' ) {
					unset( $data['screenshot'][ $k ] );
				} else {
					$data['screenshot'][$k] = (string)$this->download_and_get_attach_id($v['screenshot']);
				}
			}
			$data['screenshot'] = array_values(array_filter($data['screenshot']));
		}

		$data['comments'] = $ql->rules( $this->rules['app_comments'] )->range( '#ItemWYPL .cont .pllist>ul>li' )->queryData();

		$shots = [];
		foreach ($data['screenshot'] as $k => $v) {
			$shots[$k] = wp_get_attachment_image_url($v);
		}

		$data['app'] = $ql->rules( $this->rules['app'] )->range( 'body' )->query()->getData(function ($item) use ($shots) {
			$ql = QueryList::html($item['post_content']);
			$attrs = $ql->find('img')->attrs('src');
			if (count($attrs->all())) {
				foreach ($attrs->all() as $k => $v) {
					$ql->find('img')->eq($k)->attr('src', $shots[$k]);
				}
			}

			$ql->find('img')->removeAttr('preview');
			$item['post_content'] = $ql->find('')->html();
			return $item;

		});

		$data['meta'] = $ql->rules( $this->rules['meta'] )->range( '.softinforel.Msoftinforel > .softinfoBox ul.softinfo' )->queryData();

		$data['download_link'] = $ql->find( '#down_url:nth-child(5) li:first a' )->attr( 'href' );

		$data['app']                 = $data['app'][0];
		$data['meta']                = $data['meta'][0];
		$data['app']['seo_desc']     = wp_trim_words( $data['app']['seo_desc'], 60 );
		$data['app']['seo_keywords'] = $ql->find( 'meta[name="keywords"]' )->attr( 'content' );

		$data['app']['post_title'] = strip_tags( $data['app']['post_title'] );
		$data['app']['seo_title']  = str_replace(' ', '',$data['app']['post_title']) . "_" . str_replace(' ','',$data['app']['seo_title']);


		$data['app']['icon'] = $this->download_and_get_attach_id($data['app']['icon']);

		return $data;
	}

	/*获取文章列表*/
	public function get_apps( $url, $page ) {
		if ( $page !== 1 ) {
			$url = $url . '/' . $page;
		}
		$rules = $this->rules['app_list'];
		$list  = QueryList::get( $url )->rules( $rules )->range( '#soft_list .applist' )->queryData();
		foreach ( $list as $key => $val ) {
			$has_post = get_page_by_title( trim($val['title']), OBJECT, 'post' );
			if ( $has_post && $has_post->ID ) {
				unset( $list[ $key ] );
			}
		}

		return $list;
	}

	/*获取分页情况*/
	public function get_pages() {
		$url = $_POST['url'];
		$res = QueryList::get( $url )->find( '#soft_list.left_box .page span' )->text();

		wp_send_json( [ 'code' => 200, 'data' => $res ] );
		wp_die();
	}

	/*添加文章*/
	public function add_post( $data, $term_id) {
		$post = $data['app'];
		$meta = $data['meta'];
		$screenshot = $data['screenshot'];
		$comments = $data['comments'];
		$icon = wp_get_attachment_image_url($post['icon']);
		$post_id    = wp_insert_post([
			'post_title' => $post['post_title'],
			'post_content' => $post['post_content'],
			'post_status'  => 'publish'
		]);

		wp_set_object_terms($post_id,$term_id,'category');
		update_post_meta( $post_id, 'icon', $icon );  //APP图标
		update_post_meta( $post_id, 'screenshot', $screenshot );    //APP截图
		if (strtolower( $meta['platform'] ) === 'android') {
			update_post_meta( $post_id, 'android', $data['download_link'] );  //安卓APP下载地址
		} else {
			update_post_meta( $post_id, 'ios', $data['download_link'] );  //苹果APP下载地址
		}

		update_post_meta( $post_id, 'size', $meta['size'] );  //APP大小
		update_post_meta( $post_id, 'version', $meta['version'] );  //版本
		update_post_meta( $post_id, 'type', $meta['type'] );  //软件类型
		update_post_meta( $post_id, 'create_time', $meta['create_time'] );  //更新时间
		update_post_meta( $post_id, 'auth', $meta['auth'] );  //软件授权
		update_post_meta( $post_id, 'language', $meta['language'] );  //软件语言
		update_post_meta( $post_id, 'platform', $meta['platform'] );  //应用平台
		/*SEO*/
		update_post_meta( $post_id, 'title', $post['seo_title'] );
		update_post_meta( $post_id, 'keywords', $post['seo_keywords'] );
		update_post_meta( $post_id, 'description', $post['seo_desc'] );

		foreach ($comments as $comment) {
			wp_insert_comment( [
				'comment_author'  => '冬瓜网友',
				'comment_post_ID' => $post_id,
				'comment_content' => str_replace('华军','冬瓜',$comment['comment_content']),
				'comment_date'    => get_gmt_from_date( '20' . $comment['comment_date'] )
			] );
		}

		return true;
	}

	public function run() {
		$param    = $_POST;
		$app_list = $this->get_apps( $param['category_link'], $param['paged'] );
		$term_id  = $param['term_id'];
		$count = 0;
		foreach ( $app_list as $k => $app ) {
			$single_app = $this->get_app( $app['url'] );

			$res = $this->add_post($single_app,$term_id);
			if ($res) {$count++;}
		}

		wp_send_json( [ 'code' => 200, 'data' => $res, 'list' => $app_list ] );
		wp_die();
	}
}

$collection = new Collection();